package com.acme.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.acme.entity.ContactUsForm;

@Controller
public class RequestPlanController {
	@Autowired @Qualifier("contactUsEmail")
	SimpleMailMessage contactUsEmail;
	
	@Autowired
	JavaMailSender mailSender;
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	@RequestMapping(value="RequestPlan", method = RequestMethod.GET)
	public ModelAndView Form(){
		ModelAndView m = new ModelAndView("RequestPlan", "contactUsForm", new ContactUsForm());
		return m;
	}
	
	@RequestMapping(value="RequestPlan", method = RequestMethod.POST)
	public String PostForm(@ModelAttribute("contactUsForm") ContactUsForm form){
		logger.info(form.toString());
		sendContactUsEmail(form);
		return "ContactUs";
	}
	
	private void sendContactUsEmail(ContactUsForm form) {
		SimpleMailMessage email = new SimpleMailMessage();
		email.setFrom(contactUsEmail.getFrom());
		email.setTo(contactUsEmail.getTo());
		email.setSubject(contactUsEmail.getSubject());
		email.setText(String.format(contactUsEmail.getText(),
									form.getfName(), form.getlName(), 
									form.getAddress1(), form.getAddress2(),
									form.getCity(), form.getState(), form.getZip(),
									form.getEmail(), form.getPhoneNum(), 
									form.getTimeToCall(), form.getAge()));
		mailSender.send(email);
	}
}
